#!/usr/bin/env python3
# -*- coding: utf-8 -*-

import click
import yaml
import os
from proxy_server import start_proxy

@click.group()
def cli():
    """浏览器代理工具 - 帮助调试前端请求"""
    pass

@cli.command()
@click.option('--host', '-h', help='代理服务器监听地址 (默认从配置文件读取，如无配置则为0.0.0.0)')
@click.option('--port', '-p', type=int, help='代理服务器监听端口 (默认从配置文件读取，如无配置则为8080)')
@click.option('--config', '-c', default='config.yaml', help='配置文件路径')
@click.option('--log-level', '-l', 
              type=click.Choice(['DEBUG', 'INFO', 'WARNING', 'ERROR', 'CRITICAL'], case_sensitive=False),
              help='日志级别 (覆盖配置文件设置)')
def start(host, port, config, log_level):
    """启动代理服务器"""
    # 将log_level转换为大写，保持一致性
    if log_level:
        log_level = log_level.upper()
    
    # 如果没有指定host和port，从配置文件读取
    if host is None or port is None:
        try:
            with open(config, 'r') as f:
                config_data = yaml.safe_load(f)
                server_config = config_data.get('server', {}).get('proxy', {})
                if host is None:
                    host = server_config.get('host', '0.0.0.0')
                if port is None:
                    port = server_config.get('port', 8080)
        except:
            # 配置文件读取失败，使用默认值
            if host is None:
                host = '0.0.0.0'
            if port is None:
                port = 8080
    
    click.echo(f"启动代理服务器: {host}:{port}")
    click.echo(f"配置文件: {config}")
    
    start_proxy(host, port, config, log_level)

@cli.command()
@click.option('--config', '-c', default='config.yaml', help='配置文件路径')
def init(config):
    """初始化配置文件"""
    if os.path.exists(config):
        click.echo(f"配置文件 {config} 已存在")
        return
    
    default_config = {
        'server': {
            'proxy': {
                'host': '0.0.0.0',
                'port': 8080,
                'default_target_port': 80
            },
            'web': {
                'host': '0.0.0.0',
                'port': 5001
            },
            'system_proxy': {
                'host': '127.0.0.1',
                'port': 8080
            }
        },
        'logging': {
            'level': 'INFO'
        },
        'rules': [
            {
                'pattern': 'api.example.com',
                'target': {
                    'scheme': 'http',
                    'host': 'localhost',
                    'port': 8000
                }
            }
        ]
    }
    
    with open(config, 'w') as f:
        yaml.dump(default_config, f, default_flow_style=False, allow_unicode=True)
    
    click.echo(f"配置文件已创建: {config}")
    click.echo("请修改配置文件中的规则以匹配您的需求")

if __name__ == '__main__':
    cli() 